package com.mjk.common.core.rmq;


import com.mjk.common.core.rmq.conf.RmqProperty;
import com.mjk.common.core.rmq.mq.PublishProxy;
import com.mjk.common.core.rmq.mq.RmqChannel;
import com.mjk.common.core.rmq.mq.SubscribeProxys;
import lombok.Getter;

/**
 * 
* @author mjk  
* @date 2019年3月8日
 */
public class EventBus {

	private EventBus(){}

	@Getter
	private static RmqChannel channel;

	private static SubscribeProxys subscribeProxys;

	private static PublishProxy proxy;

	public static void init(RmqProperty property) {
		channel = new RmqChannel(property);
		channel.connect();
		subscribeProxys = new SubscribeProxys(channel);
		proxy = new PublishProxy(channel);
	}

	public static void destroy() {
		channel.disConnect();
	}
	/**
	 *
     */
	public static int check(Object subscriber) {
		if (subscriber == null) {
			return EventErrorCode.SUBSCRIBE_LISTEN_INVALID;
		}
		if (channel == null) {
			return EventErrorCode.CHANNEL_INITIALIZE_EXCEPTION;
		}
		if (proxy == null) {
			return EventErrorCode.CHANNEL_INITIALIZE_EXCEPTION;
		}
		return EventErrorCode.SUCCEED;
	}
	/**
     *
     */
	public static void registerListener(Object subscriber) {
		int error = check(subscriber);
		if (error != EventErrorCode.SUCCEED) {
			return;
		}
        subscribeProxys.doProxy(subscriber);
    }

	/**
     */
	public static int publish(Object event) {
		int error = check(event);
		if (error != EventErrorCode.SUCCEED) {
			return error;
		}
		return proxy.publish(event);
	}
	
	
	public static int publish(Object event, int ttl) {
		int error = check(event);
		if (error != EventErrorCode.SUCCEED) {
			return error;
		}
		return proxy.publish(event, ttl);
	}
	/**
	 * 发送广播
     */
	public static int broadcast(Object event) {
		int error = check(event);
		if (error != EventErrorCode.SUCCEED) {
			return error;
		}
		return proxy.broadcast(event);
	}

	public static int broadcast(Object event, int ttl) {
		int error = check(event);
		if (error != EventErrorCode.SUCCEED) {
			return error;
		}
		return proxy.broadcast(event, ttl);
	}
	/**
     */
	public static int p2p(Object event) {
		int error = check(event);
		if (error != EventErrorCode.SUCCEED) {
			return error;
		}
		return proxy.p2p(event);
	}
	
	
	public static int p2p(Object event, int ttl) {
		int error = check(event);
		if (error != EventErrorCode.SUCCEED) {
			return error;
		}
		return proxy.p2p(event, ttl);
	}
	public static void startSubscribe() {
		subscribeProxys.start();
	}
}
